<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/7/24
 * Time: 09:17
 */

namespace app\index\controller;

use app\index\controller\Base;
use app\system\api\MemberApi;
use app\index\service\OAuth2ClientService;
use app\system\api\UserApi;
use app\system\api\UserLogApi;
use app\system\model\UserPicture;
use app\system\model\UserLog;

class File extends Base
{
    protected $Accept_Type = array('avatar','gallery','other','bbs','ID','bg');

    //文件 form 上传
    public function upload()
    {
        //$getPost = array_merge($_GET,$_POST);
        $this->client_id = I('get.client_id','');
        addLog("File/upload",$_GET,$_POST,$this->client_id."调用文件上传接口!");
        // addLog("File/upload",$_GET,$_FILES,$this->client_id." ==before == FIles上传接口!");

        if (IS_POST) {
            $uid  = $this->_param('uid',0);
            $type = $this->_param('type','');

            if(empty($type)) $type = I('get.type','');
            if(!in_array($type,$this->Accept_Type)) $this->apiReturnErr("文件类型不支持!");

            if($uid <= 0) $this->apiReturnErr("用户ID非法!");

            $result = apiCall(UserApi::GET_INFO,[$uid]);
            if(!$result['status']) $this->apiReturnErr("用户ID不存在!");
            if(!isset($_FILES['image'])) $this->apiReturnErr("文件对象必须为image!");

            $result['info'] = "";
            //2.再上传到自己的服务器，
            //TODO:也可以上传到QINIU上
            /* 返回标准数据 */

            /* 调用文件上传组件上传文件 */
            $Picture = new UserPicture();
            $extInfo = array('uid' => $uid,'imgurl' => C('UPLOAD_URL'),'type'=>$type);
            // addLog("File/upload",$_GET,$_FILES,$this->client_id." ==after == FIles上传接口!");
            $info = $Picture->upload(
                $_FILES,
                C('USER_PICTURE_UPLOAD')
                ,$extInfo
            );
            // addLog("---/File/upload",$_GET,$info,$this->client_id."调用---文件上传接口!");
            /* 记录图片信息 */
            if($info){
                if($type == 'bg'){
                    flushUinfo($uid);
                    //更新用户背景图
                    apiCall(MemberApi::SAVE_BY_ID,[$uid,['bg_img'=>$info['image']['id']]]);
                    $info['image']['api_img_url'] = C('API_URL').'/picture/index?id='.$info['image']['id'];
                    $this -> apiReturnSuc($info['image']);
                }elseif($type == 'avatar'){
                    flushUinfo($uid);
                    //更新用户 - 更新奖励
                    $info['image']['msg'] = $this -> saveToUserHead($uid,$info['image']['id']);
                    $head = C('API_URL').'/picture/index?id='.$info['image']['id'];
                    $info['image']['api_img_url'] = $head;
                    $this -> apiReturnSuc($info['image']);
                }elseif($type == 'bbs'){
                    $this -> apiReturnSuc($info);
                }else{
                    $this -> apiReturnSuc($info);
                }
            } else {
                $this->apiReturnErr($Picture->getError());
            }
        }
    }

    //文件 curl 上传
    public function curl_upload()
    {

        $this->client_id = I('get.client_id','');
        addLog("File/curl_upload",$_GET,'',$this->client_id."调用文件上传接口!");
        // addLog("File/upload2",$_GET,$_FILES,$this->client_id." ==before == FIles上传接口!");

        if (IS_POST) {
            $uid   = $this->_post('uid',0);
            $type  = $this->_post('type','');
            $fdata = $this->_post('fdata','');
            $fname = $this->_post('fname','');
            $ftype = $this->_post('ftype','');
            if(empty($type)) $type = I('get.type','');
            if(!in_array($type,$this->Accept_Type)) $this->apiReturnErr("
                !");

            if($uid <= 0) $this->apiReturnErr("用户ID非法!");
            $result = apiCall(UserApi::GET_INFO,[$uid]);
            if(!$result['status']) $this->apiReturnErr("用户ID不存在!");

            /* 调用文件上传组件上传文件 */
            $Picture = new UserPicture();
            $extInfo = array('uid' => $uid,'imgurl' => C('UPLOAD_URL'),'type'=>$type);
            $info = $Picture->curl_upload(
                ['data'=>$fdata,'name'=>$fname,'type'=>$ftype],
                C('USER_PICTURE_UPLOAD'),
                $extInfo
            );
            /* 记录图片信息 */
            if($info){
                if($type == 'avatar'){
                    //保存到用户信息表
                    $info['image']['msg'] = $this->saveToUserHead($uid,$info['image']['id']);
                    $head = C('API_URL').'/picture/index?id='.$info['image']['id'];
                    $info['image']['api_img_url'] = $head;
                    $this->apiReturnSuc($info['image']);
                }elseif($type == 'bbs'){
                    $this->apiReturnSuc($info);
                }else{
                    $this->apiReturnSuc($info);
                }

            } else {
                $this->apiReturnErr($Picture->getError());
            }

        }
    }

    /**
     * 保存图片ID到用户信息的头像字段中 - 包含是否奖励
     * @param $uid      用户ID
     * @param $pic_id   图片ID
     * @return mixed
     */
    public function saveToUserHead($uid,$pic_id){
        $result = apiCall(MemberApi::SAVE_BY_ID,[$uid,['head'=>$pic_id]]);
        if(false === $result['status']) return $this->apiReturnErr('err1');
        $result = apiCall(UserLogApi::FIRST_AVATAR,[$uid]);
        if(false === $result['status']) return $this->apiReturnErr('err2');
        return $result['info'];
    }

    public function getSupportMethod(){

    }

    /**
     * ajax返回
     * @param $data
     * @internal param $i
     */
    protected function apiReturnSuc($data){
        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode(array('code'=>0,'data'=>$data,'notify_id'=>$this->notify_id),false));
    }

    /**
     * ajax返回，并自动写入token返回
     * @param $data
     * @param int $code
     * @internal param $i
     */
    protected function apiReturnErr($data,$code=-1){
        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode(array('code'=>$code,'data'=>$data,'notify_id'=>$this->notify_id),false));
    }
    public function _initialize(){}
    public function decodePost(){}
}